package com.devilwwj.http;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import com.devilwwj.http.callback.FileCallback;
import com.devilwwj.http.callback.JSONArrayReaderCallback;
import com.devilwwj.http.callback.JSONCallback;
import com.devilwwj.http.callback.JSONReaderCallback;
import com.devilwwj.http.callback.StringCallback;
import com.devilwwj.http.core.Request;
import com.devilwwj.http.core.RequestManager;
import com.devilwwj.http.entities.FileEntity;
import com.devilwwj.http.entities.Module;
import com.devilwwj.http.entities.User;
import com.devilwwj.http.exception.HttpException;

import java.io.File;
import java.util.ArrayList;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStop() {
        super.onStop();
        RequestManager.getInstance().cancelRequest(toString());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnRequest:
//                testHttpPostOnSubThread();
                testHttpPostOnSubThreadForGeneric();
//                testHttpPostOnSubThreadForDownload();
//                testHttpPostOnSubThreadForDownloadProgress();
//                testHttpPostOnSubThreadForGenericLoadMore();
//                testHttpForJsonReaderArray();
//                testUploadProgressUpdated();
                break;
        }
    }
    // TODO 提供各种数据类型的测试方法
    private void testHttpPostOnSubThread() {
        String url = "http://api.stay4it.com/v1/public/core/?service=user.login";
        String content = "account=stay4it&password=123456";
        Request request = new Request(url, Request.RequestMethod.POST);
        request.setCallback(new JSONCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("onsuccess", "testHttpGet reture:" + result);
            }

            @Override
            public void onFailure(HttpException e) {
                if (e.statusCode == 403) {
                    if ("password incorrect".equals(e.responseMessage)) {
                        // TODO
                    } else if ("token invalid".equals(e.responseMessage)) {
                        // TODO relogin
                    }
                }
            }
        });
        // global exception handler
        request.setGlobalExceptionListener(this);
        request.content = content;
        RequestManager.getInstance().performRequest(request);
    }

    public void testHttpPostOnSubThreadForGeneric() {

        String url = "http://api.stay4it.com/v1/public/core/?service=user.login";
        String content = "account=stay4it&password=123456";
        Request request = new Request(url, Request.RequestMethod.POST);
        String path = Environment.getExternalStorageDirectory() + File.separator + "json.tmp";
        request.setCallback(new JSONReaderCallback<User>() {

            @Override
            public void onSuccess(User result) {
//                TODO insert into db
//                ArrayList<User>
                Log.e("onSuccess", "testHttpGet return:" + result.toString());
            }

            @Override
            public void onFailure(HttpException e) {
                e.printStackTrace();
            }


        }.setCachePath(path));
        request.content = content;
        request.maxRetryCount = 0;
        RequestManager.getInstance().performRequest(request);

    }

    public void testHttpPostOnSubThreadForGenericPostRequest() {

        String url = "http://api.stay4it.com/v1/public/core/?service=user.login";

        String content = "account=stay4it&password=123456";
        Request request = new Request(url, Request.RequestMethod.POST);
        request.setCallback(new JSONReaderCallback<User>() {
            @Override
            public User postRequest(User user) {
                //                TODO insert into db
//                TODO edit user
                Log.e("stay", "postRequest return:" + user.toString());
                user.email = "xxxx@xxx.com";
                return user;
            }

            @Override
            public void onSuccess(User result) {
//                ArrayList<User>
                Log.e("stay", "onSuccess return:" + result.toString());
            }

            @Override
            public void onFailure(HttpException e) {
                e.printStackTrace();
            }
        });
        request.content = content;
        request.maxRetryCount = 0;
        RequestManager.getInstance().performRequest(request);

    }


    public void testHttpPostOnSubThreadForGenericLoadMore() {

        String url = "http://api.stay4it.com/v1/public/core/?service=user.getAll";
        url += "&timestamp=" + System.currentTimeMillis() + "&count=30";
        Request request = new Request(url, Request.RequestMethod.GET);
        request.setCallback(new JSONCallback<ArrayList<Module>>() {

            @Override
            public ArrayList<Module> preRequest() {
//                TODO fetch data
                return null;
            }

            @Override
            public ArrayList<Module> postRequest(ArrayList<Module> modules) {
//                TODO insert into db
                return modules;
            }

            @Override
            public void onSuccess(ArrayList<Module> result) {
                Log.e("stay", "result" + result.size());


            }

            @Override
            public void onFailure(HttpException e) {
                e.printStackTrace();
            }
        });
        RequestManager.getInstance().performRequest(request);

    }

    public void testHttpForJsonReaderArray() {

        String url = "http://api.stay4it.com/v1/public/core/?service=user.getAll";
        url += "&timestamp=" + System.currentTimeMillis() + "&count=30";
        Request request = new Request(url, Request.RequestMethod.GET);
        String path = Environment.getExternalStorageDirectory() + File.separator + "jsonarray.tmp";
        request.setCallback(new JSONArrayReaderCallback<Module>() {

            @Override
            public ArrayList<Module> preRequest() {
//                TODO fetch data
                return null;
            }

            @Override
            public ArrayList<Module> postRequest(ArrayList<Module> modules) {
//                TODO insert into db
                return modules;
            }

            @Override
            public void onSuccess(ArrayList<Module> result) {
                Log.e("stay", "result" + result.size());


            }

            @Override
            public void onFailure(HttpException e) {
                e.printStackTrace();
            }
        }.setCachePath(path));
        RequestManager.getInstance().performRequest(request);

    }



    public void testHttpPostOnSubThreadForDownload() {

        String url = "http://api.stay4it.com/v1/public/core/?service=user.login";
        String content = "account=stay4it&password=123456";
        Request request = new Request(url, Request.RequestMethod.POST);
        String path = Environment.getExternalStorageDirectory() + File.separator + "demo.txt";
        request.setCallback(new FileCallback() {


            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onFailure(HttpException e) {
                e.printStackTrace();
            }
        }.setCachePath(path));
        request.content = content;
        RequestManager.getInstance().performRequest(request);
    }

    public void testHttpPostOnSubThreadForDownloadProgress() {

        String url = "http://api.stay4it.com/uploads/test.jpg";
        Request request = new Request(url, Request.RequestMethod.GET);
        String path = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
        request.setCallback(new FileCallback() {
            @Override
            public void onProgressUpdate(int state, int curLen, int totalLen) {
                Log.e("stay", "download:" + curLen + "/" + totalLen);
                for (int i = 0; i < 10000; i++) {

                }
            }

            @Override
            public void onSuccess(String path) {
                Log.e("stay", path);
            }

            @Override
            public void onFailure(HttpException e) {
            }
        }.setCachePath(path));
        request.setEnableProgressUpdated(true);
        RequestManager.getInstance().performRequest(request);
    }


    public void testHttpPostOnSubThreadForDownloadProgressCancelTest() {
        String url = "http://api.stay4it.com/uploads/test.jpg";
        final Request request = new Request(url, Request.RequestMethod.GET);
//        final RequestTask task = new RequestTask(request);
        String path = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
        request.setCallback(new FileCallback() {
            @Override
            public void onProgressUpdate(int state, int curLen, int totalLen) {
                Log.e("stay", "download:" + curLen + "/" + totalLen);
                if (curLen * 100l / totalLen > 50) {
//                    task.cancel(true);
//                    request.cancel();
                }
            }



            @Override
            public void onSuccess(String path) {

                Log.e("stay", path);
            }

            @Override
            public void onFailure(HttpException e) {
                if (e.errorType == HttpException.ErrorType.CANCEL) {

                }
                e.printStackTrace();
            }
        }.setCachePath(path));
        request.setEnableProgressUpdated(true);
        request.setTag(toString());
        RequestManager.getInstance().performRequest(request);
    }

    public void testUploadProgressUpdated() {
        String url = "http://api.stay4it.com/v1/public/core/?service=user.updateAvatar";
        final Request request = new Request(url, Request.RequestMethod.POST);

        request.addHeader("Connection", "Keep-Alive");
        request.addHeader("Charset", "UTF-8");
        request.addHeader("Content-Type", "multipart/form-data;boundary=7d4a6d158c9");

        String path = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";

        ArrayList<FileEntity> entities = new ArrayList<FileEntity>();
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileName(path.substring(path.lastIndexOf("/") + 1));
        fileEntity.setFilePath(path);
        fileEntity.setFileType("image/png");
        entities.add(fileEntity);

        request.content = "stay4it";
        request.fileEntities = entities;
//        UploadUtil.upload(out, "stay4it", entities);


        request.setCallback(new StringCallback() {
            @Override
            public void onProgressUpdate(int state, int curLen, int totalLen) {
                Log.e("stay", "state=" + state + " onprogressUpdated:" + curLen + "/" + totalLen);
            }



            @Override
            public void onSuccess(String result) {
                Log.e("stay", result);
            }

            @Override
            public void onFailure(HttpException e) {

            }
        });
        request.setEnableProgressUpdated(true);
        request.setTag(toString());
        RequestManager.getInstance().performRequest(request);
    }


}
